package com.itcast.donkey.activity;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itcast.donkey.R;
import com.itcast.donkey.adapters.InMenuAdapter;
import com.itcast.donkey.adapters.SecondInItemAdapter;
import com.itcast.donkey.adapters.TravelInItemAdapter;
import com.itcast.donkey.infterfaces.InMenuOnClickListener;
import com.itcast.donkey.modles.TravelInHeadImageModels;
import com.itcast.donkey.modles.TravelInItemModels;
import com.itcast.donkey.modles.UriModles;


import java.io.IOException;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/9/2.
 */
public class TravelInItemActiity extends AppCompatActivity implements InMenuOnClickListener {
    private ImageView logo;
    private ImageView download;
    private ImageView start;
    private ImageView share;
    private ImageView comment;
    private ImageView iv_menu;

    private RecyclerView recyclerView;
    private SecondInItemAdapter adapter;
    private TravelInItemModels travelInItemModels;

    private RecyclerView menu_recyclerView;
    private InMenuAdapter menuAdapter;

    private RelativeLayout menu_view;

    private String id;
    private String idHead;
    private String trueId;

    LinearLayoutManager layoutManager;
    private boolean isCollect = true;

    private TravelInItemAdapter travelInItemAdapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_travel_in_item);

        //得到一级页面传的值
        id = getIntent().getStringExtra("id");
        //得到从头像的二级页面传来的值
        idHead = getIntent().getStringExtra("headID");
        if (id != null) {
            trueId = id;
        }
        if (idHead != null) {
            trueId = idHead;
        }

        initView();
        getData();
        getMenuData();
        initEvent();

    }

    private void initView() {
        logo = (ImageView) findViewById(R.id.logo);
        download = (ImageView) findViewById(R.id.download);
        start = (ImageView) findViewById(R.id.start);
        share = (ImageView) findViewById(R.id.share);
        comment = (ImageView) findViewById(R.id.comment);
        iv_menu = (ImageView) findViewById(R.id.iv_menu);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        menu_recyclerView = (RecyclerView) findViewById(R.id.menu_recyclerView);
        menu_view = (RelativeLayout) findViewById(R.id.menu_view);


    }


    private void getMenuData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(UriModles.TRAVEL_FRONT_IN_Item_URL + trueId + UriModles.TRAVEL_END_IN_Item_URL)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String resultMenu = response.body().string();
                        Gson gson = new Gson();
                        travelInItemModels = gson.fromJson(resultMenu, TravelInItemModels.class);
                        if (travelInItemModels.getTrip_days().size() > 0) {
                            handler.sendEmptyMessage(4);
                        } else {
                            handler.sendEmptyMessage(3);
                        }
                    }
                });

            }
        }).start();
    }


    private void getData() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(UriModles.TRAVEL_FRONT_IN_Item_URL + trueId + UriModles.TRAVEL_END_IN_Item_URL)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();
                        travelInItemModels = gson.fromJson(result, TravelInItemModels.class);
                        if (travelInItemModels.getTrip_days().size() > 0) {
                            handler.sendEmptyMessage(1);
                        }
                    }
                });
            }
        }).start();
    }

    private void initEvent() {

        logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(TravelInItemActiity.this, MainActivity.class);
//                startActivity(intent);
                finish();
            }
        });
        download.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Notification.Builder builder = new Notification.Builder(TravelInItemActiity.this);
                builder.setTicker("正在下载");
                builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_chanyouji_logo));
                builder.setContentTitle("蝉游记");
                builder.setContentText("正在下载");
                builder.setSmallIcon(R.mipmap.ic_launcher);

                nm.notify(10, builder.build());
            }
        });
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCollect) {
                    start.setBackgroundResource(R.mipmap.collection_checked_b);
                    isCollect = false;
                    Toast.makeText(TravelInItemActiity.this, "已收藏", Toast.LENGTH_SHORT).show();
                } else {
                    start.setBackgroundResource(R.mipmap.collection_b);
                    Toast.makeText(TravelInItemActiity.this, "已取消", Toast.LENGTH_SHORT).show();
                    isCollect = true;
                }
            }
        });
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(TravelInItemActiity.this, LoginActivity.class);
                startActivity(intent2);
            }
        });
        iv_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menu_view.setVisibility(View.VISIBLE);
                iv_menu.setVisibility(View.GONE);
            }
        });
        menu_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menu_view.setVisibility(View.GONE);
                iv_menu.setVisibility(View.VISIBLE);
            }
        });

    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(TravelInItemActiity.this, "解析失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    adapter = new SecondInItemAdapter(TravelInItemActiity.this, travelInItemModels);
                    recyclerView.setAdapter(adapter);
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(TravelInItemActiity.this);
                    recyclerView.setLayoutManager(linearLayoutManager);
                    break;
                case 2:
                    Toast.makeText(TravelInItemActiity.this, "获取网络失败", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(TravelInItemActiity.this, "菜单出错了", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    menuAdapter = new InMenuAdapter(TravelInItemActiity.this, travelInItemModels);
                    menu_recyclerView.setAdapter(menuAdapter);
                    //绑定点击事件
                    menuAdapter.setMyOnItemClick(TravelInItemActiity.this);
                    layoutManager = new LinearLayoutManager(TravelInItemActiity.this);
                    menu_recyclerView.setLayoutManager(layoutManager);

                    break;
            }

        }
    };

    //分享
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("QQ空间分享测试");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }

    @Override
    public void onMenuClick(int position) {


        recyclerView.scrollToPosition(position + 1);
        adapter.notifyDataSetChanged();

        //菜单消失
        menu_view.setVisibility(View.GONE);
        iv_menu.setVisibility(View.VISIBLE);
    }
}
